package org.csu.jpetstore_users_backend_pj.exception;


import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.csu.jpetstore_users_backend_pj.result.CommonResponse;
import org.csu.jpetstore_users_backend_pj.result.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //缺少参数
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(code = HttpStatus.OK)
    @ResponseBody
    public CommonResponse<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.MissingParam.getCode(),ResponseCode.MissingParam.getDescription());
    }

    //参数格式不正确
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(code = HttpStatus.OK)
    @ResponseBody
    public CommonResponse<String> handleConstraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.Invalid.getCode(),ResponseCode.Invalid.getDescription());
    }

    //unique或id重复
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(code = HttpStatus.OK)
    @ResponseBody
    public CommonResponse<String> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        log.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.Duplicate.getCode(),ResponseCode.Duplicate.getDescription() );
    }

    //服务器异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.OK)
    @ResponseBody
    public CommonResponse<String> handleException(Exception e) {
        log.error("捕获到未处理的服务器异常！", e); // 使用 'e' 作为第二个参数;
        return CommonResponse.createForError(1,e.getMessage());
    }
}
